#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <iostream>

const int backlog = 10;

enum {
    SocketErr = 1,
    BindErr
};

class Sock
{
public:
    Sock()
        :_root_fd(-1)
    { }

    int Socket()
    {
        _root_fd = socket(AF_INET, SOCK_STREAM, 0);
        if(_root_fd < 0) {
            std::cerr << "socket err" << std::endl;
            exit(SocketErr);
        }
        return _root_fd;
    }

    bool Bind(const uint16_t port)
    {
        sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);
        if(bind(_root_fd, (const sockaddr*)&local, sizeof(local)) < 0) {
            std::cerr << "bind err" << std::endl;
            return false;
        }
        return true;
    }

    bool Listen()
    {
        if(listen(_root_fd, backlog) < 0) {
            std::cerr << "listen err" << std::endl;
            return false;
        }
        std::cerr << "start listening..." << std::endl;
        return true;
    }

    int Accept(std::string* clientip, uint16_t* clientport)
    {
        sockaddr_in client;
        memset(&client, 0, sizeof(client));
        socklen_t len = 0;
        int fd = accept(_root_fd, (sockaddr*)&client, &len);
        if(fd < 0) {
            std::cerr << "accept err" << std::endl;
            return -1;
        }
        char buff[32]; buff[0] = 0;
        *clientip = inet_ntop(AF_INET, &client.sin_addr, buff, sizeof(buff));
        *clientport = ntohs(client.sin_port);
        std::cout << "accept done..." << std::endl;
        return fd;
    }

    bool Connect(const std::string& ip, const uint16_t port)
    {
        sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        server.sin_port = htons(port);
        if(connect(_root_fd, (const sockaddr*)&server, sizeof(server)) < 0) {
            std::cerr << "connect err:" << strerror(errno) << std::endl;
            return false;
        }
        std::cout << "connect..." << std::endl;
        return true;
    }

private:
    int _root_fd;
};